package com.lty.protocol.tcp.handler;

import com.lty.protocol.tcp.TcpProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName EncoderHandler
 * @Description tcp客户端与服务端通信编码handler
 * @Author Administrator
 */
@Slf4j
public class EncoderHandler extends MessageToByteEncoder {

    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (msg instanceof TcpProtocol) {
            TcpProtocol protocol = (TcpProtocol) msg;
            out.writeByte(protocol.getHeader());
            out.writeInt(protocol.getLen());
            out.writeBytes(protocol.getData());
            out.writeByte(protocol.getTail());
            log.debug("数据编码成功：" + out);
        } else {
            log.info("不支持的数据协议：" + msg.getClass() + "\t期待的数据协议类是：" + TcpProtocol.class);
        }
    }
}
